package com.bidevalution.business.function;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

public class SortOfArrayFunction extends AbstractFunction {
	private Logger logger = LogManager.getLogger(getClass());
	public SortOfArrayFunction(FunctionInitializer functionInitializer) {
		super();
	}
	/**
	 * 对数组在值进行排序
	 * <p>Description: </p>
	 * @param env
	 * @param arg1 数组
	 * @param arg2  0顺序 1 倒序
	 * @return 返回数组
	 * @see com.googlecode.aviator.runtime.function.AbstractFunction#call(java.util.Map, com.googlecode.aviator.runtime.type.AviatorObject, com.googlecode.aviator.runtime.type.AviatorObject)
	 */
	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1,
			AviatorObject arg2) {
		String paramValue = FunctionUtils.getStringValue(arg1, env);
		List<String> priceList = new LinkedList<String>(
				Arrays.asList(paramValue.split(",")));
		Integer sortValue = Integer.valueOf(arg2.getValue(env).toString());
		Collections.sort(priceList, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				try {
					if (sortValue == 0) {
						return new BigDecimal(o1).compareTo(new BigDecimal(o2));
					} else if (sortValue == 1) {
						return new BigDecimal(o2).compareTo(new BigDecimal(o1));
					}
				}catch (Exception e) {
					logger.error(e.getMessage(),e);
					logger.error(o1+":"+o2);
					throw e;
				}
				
				return 0;
			}
		});
		
		String result = StringUtils.collectionToDelimitedString(
				priceList, ",");
		logger.info("sortOfArray:"+result);
		return new AviatorString(result);
	}

	@Override
	public String getName() {
		return "sortOfArray";
	}

}
